package com.archive.manage.http;

import com.alibaba.fastjson2.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

public class ApacheHttpUtils {
    private static final Logger log = LoggerFactory.getLogger(ApacheHttpUtils.class);

    public static <T> T doGetOrDeleteWithRequestBody(String url, String requestBody, String method, Class<T> clazz) throws Exception {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpWithEntity httpWithEntity = new HttpWithEntity(url, method);
        HttpEntity httpEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
        httpWithEntity.setEntity(httpEntity);
        try (CloseableHttpResponse response = client.execute(httpWithEntity)) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String body = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                return JSON.parseObject(body, clazz);
            } else {
                throw new Exception("Invoke " + method + " API failed with response status: " + response.getStatusLine().getStatusCode());
            }
        }
    }

    public static <T> T doPost(String url, String requestBody, Class<T> clazz) throws Exception {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON));

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    String body = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                    return JSON.parseObject(body, clazz);
                } else {
                    throw new Exception("Invoke post API failed with response status: " + response.getStatusLine().getStatusCode());
                }
            }
        }
    }
}
